package com.jt.sevrice;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@PropertySource("classpath:/image.properties")
public class FileServiceImpl implements FileService{
    @Value("${file.localDirPath}")
    private String loalDirPath;
    @Value("${file.preUrlPath}")
    private String preUrlPath;

    @Override
    public ImageVO upload(MultipartFile file) {
        //获取文件的文件名  验证
        String filename = file.getOriginalFilename();
        filename = filename.toLowerCase();
        if (!filename.matches("jpg|png|jpeg")) {
            return null;
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (height == 0 || width == 0) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        String filePath = "D:/images";
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String dateDirPath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //文件上传路径
        String path = filePath + dateDirPath;
        String uuid = UUID.randomUUID().toString().replace("-", "");
        int index = filename.lastIndexOf(".");
        String fileType = filename.substring(index);
        //  这个就是随机的filename  随机的uuid.jpg
        String realFileName = uuid + fileType;
        //本地文件名字  磁盘+uuid+.jpg
        String localFileName = fileDir + realFileName;
        try {
            //上传文件夹
            file.transferTo(new File(localFileName));
            //虚拟文件名  2021/7/17/1264525.jpg
            String virtualPath=dateDirPath+realFileName;
            //网络路径  http://image.jt.com/2021/7/171264525.jpg
            String urlPath=preUrlPath+virtualPath;
            ImageVO imageVO1 = new ImageVO(virtualPath, urlPath, filename);
            return imageVO1;
        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }
    }

    @Override
    public void deleteFile(String virtualPath) {
        String path=loalDirPath+virtualPath;
        File file =new File(path);
        file.delete();
    }
}
